package me.yuxiaoyao.jpa.nativesql;

import me.yuxiaoyao.jpa.nativesql.annotation.EnableNativeSqlMapper;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author kerryzhang on 2020/12/16
 */


public class NativeSqlMapperRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

        // 获取EnableEcho注解的所有属性的value
        Map<String, Object> attributes = importingClassMetadata.getAnnotationAttributes(EnableNativeSqlMapper.class.getName());
        //获取package属性的value
        List<String> packages = null;
        if (attributes != null) {
            // get @EnableNativeSqlMapper(value = {})
            packages = Arrays.asList((String[]) attributes.get("value"));
        }
        // reg listener
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(ApplicationContextStartedListener.class);
        //给 ApplicationContextStartedListener.class 中注入packages
        beanDefinitionBuilder.addPropertyValue("packages", packages);
        registry.registerBeanDefinition(ApplicationContextStartedListener.class.getName(), beanDefinitionBuilder.getBeanDefinition());
    }
}
